<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Token Authentication Demo</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            color: #333;
        }

        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 500px;
            padding: 30px;
            text-align: center;
        }

        h1 {
            color: #2c3e50;
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #34495e;
        }

        input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
            box-sizing: border-box;
        }

        input:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        button {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 14px 20px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            width: 100%;
            transition: background 0.3s;
            margin-top: 10px;
        }

        button:hover {
            background: #2980b9;
        }

        .result {
            margin-top: 25px;
            padding: 15px;
            border-radius: 8px;
            background: #f8f9fa;
            text-align: left;
            max-height: 300px;
            overflow: auto;
        }

        .info-panel {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
            text-align: left;
        }

        .tab-container {
            display: flex;
            margin-bottom: 20px;
        }

        .tab {
            flex: 1;
            padding: 12px;
            background: #f1f1f1;
            border: none;
            cursor: pointer;
            font-weight: 600;
        }

        .tab.active {
            background: #3498db;
            color: white;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Token Authentication Demo</h1>

        <div class="tab-container">
            <button class="tab active" onclick="openTab(event, 'login')">Login</button>
            <button class="tab" onclick="openTab(event, 'protected')">Protected Data</button>
            <button class="tab" onclick="openTab(event, 'admin')">Admin Area</button>
        </div>

        <div id="login" class="tab-content active">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" id="username" placeholder="Enter username" value="admin">
            </div>

            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" id="password" placeholder="Enter password" value="adminpass">
            </div>

            <button onclick="login()">Login</button>
            <button onclick="loginWithHeader()" style="background: #9b59b6;">Login with Custom Header</button>

            <div class="info-panel">
                <strong>Try these users:</strong>
                <ul>
                    <li>admin / adminpass (admin role)</li>
                    <li>alice / alicepass (editor role)</li>
                    <li>bob / bobpass (viewer role)</li>
                </ul>
            </div>
        </div>

        <div id="protected" class="tab-content">
            <button onclick="getProtectedData()">Get Protected Data</button>
            <button onclick="getProtectedDataWithHeader()" style="background: #9b59b6;">Get with Custom Header</button>
            <div class="result" id="protected-result"></div>
        </div>

        <div id="admin" class="tab-content">
            <button onclick="getAdminData()">Get Admin Data</button>
            <div class="result" id="admin-result"></div>
        </div>

        <div class="result" id="result"></div>

        <div style="margin-top: 25px;">
            <button onclick="refreshToken()" style="background: #27ae60;">Refresh Token</button>
            <button onclick="logout()" style="background: #e74c3c;">Logout</button>
        </div>
    </div>

    <script>
        // 打开标签页
        function openTab(evt, tabName) {
            const tabContents = document.getElementsByClassName("tab-content");
            for (let i = 0; i < tabContents.length; i++) {
                tabContents[i].classList.remove("active");
            }

            const tabs = document.getElementsByClassName("tab");
            for (let i = 0; i < tabs.length; i++) {
                tabs[i].classList.remove("active");
            }

            document.getElementById(tabName).classList.add("active");
            evt.currentTarget.classList.add("active");
        }

        // 显示结果
        function showResult(selector, data) {
            const element = document.getElementById(selector);
            element.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
        }

        // 登录函数
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('result', {
                        message: 'Login successful! Token stored in cookies.',
                        user: data.user
                    });
                } else {
                    showResult('result', { error: data.error || 'Login failed' });
                }
            } catch (error) {
                showResult('result', { error: 'Network error: ' + error.message });
            }
        }

        // 使用自定义头登录
        async function loginWithHeader() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Custom-Auth': 'custom-header-value' // 自定义头示例
                    },
                    body: JSON.stringify({ username, password })
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('result', {
                        message: 'Login with custom header successful!',
                        user: data.user
                    });
                } else {
                    showResult('result', { error: data.error || 'Login failed' });
                }
            } catch (error) {
                showResult('result', { error: 'Network error: ' + error.message });
            }
        }

        // 获取受保护数据
        async function getProtectedData() {
            try {
                const response = await fetch('/protected', {
                    credentials: 'include' // 包含cookies
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('protected-result', data);
                } else {
                    showResult('protected-result', { error: data.error || 'Access denied' });
                }
            } catch (error) {
                showResult('protected-result', { error: 'Network error: ' + error.message });
            }
        }

        // 使用自定义头获取受保护数据
        async function getProtectedDataWithHeader() {
            try {
                const response = await fetch('/protected', {
                    headers: {
                        'X-Access-Token': getCookie('access_token') // 从cookie获取token并放入自定义头
                    }
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('protected-result', {
                        ...data,
                        note: 'This data was retrieved using a custom header'
                    });
                } else {
                    showResult('protected-result', { error: data.error || 'Access denied' });
                }
            } catch (error) {
                showResult('protected-result', { error: 'Network error: ' + error.message });
            }
        }

        // 获取管理员数据
        async function getAdminData() {
            try {
                const response = await fetch('/admin', {
                    credentials: 'include' // 包含cookies
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('admin-result', data);
                } else {
                    showResult('admin-result', { error: data.error || 'Access denied' });
                }
            } catch (error) {
                showResult('admin-result', { error: 'Network error: ' + error.message });
            }
        }

        // 刷新Token
        async function refreshToken() {
            try {
                const response = await fetch('/refresh', {
                    method: 'POST',
                    credentials: 'include'
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('result', {
                        message: 'Token refreshed successfully!',
                        note: 'Check the cookies in your browser dev tools'
                    });
                } else {
                    showResult('result', { error: data.error || 'Token refresh failed' });
                }
            } catch (error) {
                showResult('result', { error: 'Network error: ' + error.message });
            }
        }

        // 登出
        async function logout() {
            try {
                const response = await fetch('/logout', {
                    method: 'POST',
                    credentials: 'include'
                });

                const data = await response.json();

                if (response.ok) {
                    showResult('result', data);
                } else {
                    showResult('result', { error: data.error || 'Logout failed' });
                }
            } catch (error) {
                showResult('result', { error: 'Network error: ' + error.message });
            }
        }

        // 从cookie中获取值
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
            return null;
        }
    </script>
</body>
</html>